<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<web_uchet.ViewModels.ViewЗаказ>" %>
<%@ Import Namespace="Mvc.Validation" %>
<%@ Import Namespace="web_uchet.ViewModels" %>
<% web_uchet.Security.ProgramContext MData = ViewData["Master"] as web_uchet.Security.ProgramContext;%>
<div>
 <%= Html.ValidationSummary("Не удалось добавить заказ. Пожалуйста исправьте следующие ошибки:") %>
    <% using (Html.BeginForm("Create", "ViewOrder", FormMethod.Post, new { id = "create-order-form" }))
        {%>
        <fieldset>
            <%= Html.Hidden("WithDetail", false)%>
            <legend>Добавление заказа:</legend>
            <p>
                <input type="reset" value="Очистить" class="button"/>    
            </p>
            <%if (MData.Roles.Contains(web_uchet.Security.Enums.UserRoleEnum.Администратор))
              { %>
            <p>
                <label for="ManagerID">Менеджер:</label>
                <%= Html.DropDownList("ManagerID")%>
                <%= Html.ValidationMessage("ManagerID", "*")%>
            </p>
            <%} %>
            <p>
                <label for="ClientID">Клиент:</label>
                <%= Html.DropDownList("ClientID")%>
                <%= Html.ValidationMessage("ClientID", "*") %>
                <input style="margin-left:10px;" type="button" id="btn-scuser-dialog" value="Новый" class="button"/>       
            </p>                   
            <p>                
                <% Html.RenderPartial("EditorTemplates/DateTimeTemplateViewData_Calend",
                new web_uchet.Views.Shared.TemplateClasses.
                    DateTimeTemplateViewData("Дата_Поступления", "Дата_Поступления", "Дата поступления:", null)); %>
            </p>               
            <p>                
                <% Html.RenderPartial("EditorTemplates/DateTimeTemplateViewData_Calend",
                new web_uchet.Views.Shared.TemplateClasses.
                    DateTimeTemplateViewData("Дата_Назначения", "Дата_Назначения", "Дата назначения:", null)); %>
            </p>
            <%=Html.Hidden("Дата_Выполнения", string.Empty, new { id = "Дата_Выполнения" })%>
            <p>
                <label for="Описание">Описание:</label>
                <%= Html.TextArea("Описание", string.Empty, 5, 30, new { @class = "input-box", id = "Описание" })%>
                <%= Html.ValidationMessage("Описание", "*") %>
            </p>          
            <p>
                <label for="ExecutiveID">Исполнитель:</label>
                <%= Html.DropDownList("ExecutiveID")%>
                <%= Html.ValidationMessage("ExecutiveID", "*") %>
            </p> 
            <p>
                <label for="Цена">Цена:</label>
                <%= Html.TextBox("Цена", string.Empty, new { @class = "input-box", id = "Цена" })%>
                <%= Html.ValidationMessage("Цена", "*") %>
            </p>            
            <p>
                <label for="Скидка">Скидка %:</label>
                <%= Html.TextBox("Скидка", string.Empty, new { @class = "input-box", id = "Скидка" })%>
                <%= Html.ValidationMessage("Скидка", "*")%>
            </p>
            <p>
                <label>Цена с учетом скидки:</label>
                <%= Html.TextBox("Цена_со_скидкой", string.Empty, new { @class = "input-box readonly", id = "Цена_со_скидкой", disabled = "disabled"})%>
            </p>
            <p>
                <label for="Оплачено">Оплачено:</label>
                <%= Html.TextBox("Оплачено", string.Empty, new { @class = "input-box", id = "Оплачено" })%>
                <%= Html.ValidationMessage("Оплачено", "*")%>
            </p>
            <p>
                <label>Долг:</label>
                <%= Html.TextBox("Долг", string.Empty, new { @class = "input-box", id = "Долг" })%>
                <input type="button" class="button" value="Пересчитать долг, цену по скидке" id="btn-recalc-discount-cost"/>
            </p>                
            <p>
                <label for="CurrencyID">Валюта:</label>
                <%= Html.DropDownList("CurrencyID")%>
                <%= Html.ValidationMessage("CurrencyID", "*") %>
            </p>
            <p>
            <input type="submit" value="Добавить заказ" class="button"/>
            &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
            <input type="button" id="btn-add-order-with-details" value="Добавить заказ с деталями >>>" class="button"/>
            <br /><br />
              <%if ((bool)ViewData["IsAjaxRequest"])
              { %>                    
              <script type="text/javascript" id="CreatePageAjaxScript">
                  jQuery('#create-order-form').submit(function() {
                    jQuery('#create-order-form').validate();
                    if (jQuery('#create-order-form').valid())
                      DoCreateAjaxSubmit();
                      return false;
                  });

                  function DoCreateAjaxSubmit() {
                      jQuery.post('/ViewOrder/Create', jQuery('#create-order-form').serialize(), function (data) {
                          jQuery("#span-dialog").html(data);
                          jQuery("#dialog").dialog('open');
                          ReloadOrderGrid();
                      });
                  }
              </script>
            <%}%>
                          
            </p>
        </fieldset>

    <% } %>    
<div id="CreateClientDialog" title="Добавление клиента"><div><span class="ui-icon ui-icon-circle-check" 
style="float:left; margin:0 7px 50px 0;"></span><div  id="create-Client-span-dialog">
<%Html.RenderPartial("CreateClientControl", new ViewКлиент(),this.ViewData); %>
</div></div></div>
<script type="text/javascript">
                  function ShowCreateClientDialog()
                  {
                    jQuery("#CreateClientDialog").dialog('open');
                  }                  
                  jQuery(document).ready(function() {InitCreateClientDialog();});
                  function InitCreateClientDialog() {                      
                      
                        jQuery("#CreateClientDialog").dialog({
                            autoOpen: false,
                            bgiframe: true,
                            height: 400,
                            modal: true,
                            resizable: false,
                            draggable: true,
                            buttons: {
                                Отмена: function() {
                                    jQuery(this).dialog('close');
                                }
                            }
                        });
                        jQuery('#btn-scuser-dialog').click(ShowCreateClientDialog);
                }
</script>
<%= Html.ClientSideValidation<ViewЗаказ>("create-order-form")%>   
<script type="text/javascript">
    jQuery(function ($) {
        Now = new Date();
        var str = "";
        if (Now.getDate() > 9) str += Now.getDate().toString();
        else str += "0" + Now.getDate().toString();

        if ((Now.getMonth()+1) > 9) str += "-" + (Now.getMonth()+1).toString();
        else str += "-0" + (Now.getMonth()+1).toString();

        str += "-" + Now.getFullYear().toString() + " ";

        if (Now.getHours() > 9) str += Now.getHours().toString() + ":";
        else str += "0" + Now.getHours().toString() + ":";

        if (Now.getMinutes() > 9) str += Now.getMinutes().toString();
        else str += "0" + Now.getMinutes().toString();

        jQuery("#Дата_Поступления").val(str);
    });
</script>
</div>

<%--<div style="float:left; margin-top:40px; width:50%; display:none;" id="div-order-details">
<% Html.RenderPartial("OrderDetailsMultyAction", new web_uchet.Classes.JQgridProcess.OrderDetailsPartialViewData() 
   { MasterID = null, Валюты=ViewData["IEnumCurrencies"] as IEnumerable<web_uchet.Models.Валюта>, 
        Услуги_Компании=ViewData["IEnumServices"] as IEnumerable<web_uchet.Classes.ViewУслуга_Компании>}); %>
</div>--%>

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery('#btn-add-order-with-details').click(function () {
            var date = new Date();
            var theForm = jQuery('#create-order-form');
            //theForm.unbind('submit');
            jQuery('#WithDetail').val('True');

            jQuery.post('/ViewOrder/Create?fake=' + date.getMilliseconds().toString(),
                        theForm.serialize(),
        function (html) {
            //alert(html);
            jQuery('#div-html-loader').html(html);
        });

            //jQuery('#create-order-form').submit();
            //jQuery('#div-order-details').fadeIn('fast');
        });
    });
    jQuery('#btn-recalc-discount-cost').click(function () {
        ReCalcDicountCost();
    });
    function ReCalcDicountCost() {

        if (jQuery('#Цена').val() && jQuery('#Скидка').val()) {
            var Cost = parseFloat(jQuery('#Цена').val());
            var Discount = parseFloat(jQuery('#Скидка').val());
            var CostWithDiscount = Cost - (Cost * Discount / 100);
            jQuery('#Цена_со_скидкой').val(CostWithDiscount.toString());

            if (jQuery('#Оплачено').val()) {
                var Paid = parseFloat(jQuery('#Оплачено').val());
                var Credit = CostWithDiscount - Paid;
                jQuery('#Долг').val(Credit.toString());
            }
        }
    }
</script>